import React, { useState, useEffect } from "react";

import style from "./index.module.scss";
import { Editor } from "../Editor";
import { Button, message } from "antd";
import { CommentApi } from "@/api/comment";

interface IProps {
  hostId: string;
  isHostInPage: boolean;
  parentComment?: any;
  replyComment?: any;
  onReply: (arg?) => any;
}
export const EditBlock: React.FC<IProps> = ({
  // 页面id 或者 文章id
  hostId,
  // 是否在页面上
  isHostInPage,
  // 父级评论
  parentComment,
  // 回复目标评论
  replyComment,
  onReply,
}) => {
  const [loading, setLoading] = useState(false);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [content, setContent] = useState("");
  const [editInst, setEditorInstance] = useState(null);

  useEffect(() => {
    try {
      const { name, email } = JSON.parse(
        window?.localStorage.getItem("comment_user")
      );
      setName(name);
      setEmail(email);
    } catch (error) {}
  }, []);

  const submit = () => {
    let regexp = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;

    if (!regexp.test(email)) {
      message.error("请输入合法邮箱地址");
      return;
    }
    if (!content.trim()) {
      message.error("输入内容");
      return;
    }
    const data = {
      hostId,
      name,
      email,
      content,
      isHostInPage,
    };

    // 此评论的父级
    if (parentComment?.id) {
      Object.assign(data, {
        parentCommentId: parentComment.id,
      });
    }

    // 回复谁的评论
    if (replyComment) {
      Object.assign(data, {
        replyUserName: replyComment.name,
        replyUserEmail: replyComment.email,
      });
    }
    setLoading(true);
    CommentApi.addComment(data).then((res) => {
      message.success("回复成功，已提交审核！");
      setLoading(false);
      setContent("");
      editInst.setHtml("");
      onReply();
    });
    window?.localStorage.setItem(
      "comment_user",
      JSON.stringify({ name, email })
    );
  };
  return (
    <div className={style.editorBlock}>
      <div className={style.editor}>
        <Editor
          height={350}
          value={""}
          onChange={(value) => setContent(value)}
          getInstance={setEditorInstance}
        />
      </div>
      <div className={style.input}>
        <input
          value={name}
          type="text"
          placeholder="输入你的称呼"
          onChange={(e) => setName(e.target.value)}
        />
        <input
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          type="text"
          placeholder="输入您的邮箱，用于邮件通知您的评论回复(不会公开)"
        />
      </div>
      <div className={style.snedbtn}>
        <Button type="primary" onClick={submit}>
          评论
        </Button>
      </div>
    </div>
  );
};
